<template>
  <a-modal
    v-model:visible="props.visible"
    title="主题设置"
    @ok="handleOk"
    @cancel="handleCancel"
    width="500px"
  >
    <FormProvider :form="form">
      <SchemaField :schema="themeSchema" />
    </FormProvider>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { createForm } from '@formily/core';
import { FormProvider, createSchemaField } from '@formily/vue';
import { Input, FormItem } from '@formily/antdv-x3';
import { Chrome } from 'vue-color';
import { useThemeStore } from '@/stores/theme';

const props = defineProps<{
  visible: boolean;
}>();

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'ok'): void;
  (e: 'cancel'): void;
}>();

const themeStore = useThemeStore();
const form = ref(createForm());

const { SchemaField } = createSchemaField({
  components: {
    Input,
    FormItem,
    Chrome,
  },
});

const themeSchema = {
  type: 'object',
  properties: {
    primaryColor: {
      type: 'string',
      title: '主题色',
      'x-decorator': 'FormItem',
      'x-component': 'Chrome',
      default: themeStore.theme.primaryColor,
    },
    borderRadius: {
      type: 'string',
      title: '圆角大小',
      'x-decorator': 'FormItem',
      'x-component': 'Input',
      default: themeStore.theme.borderRadius,
    },
    fontSize: {
      type: 'string',
      title: '字体大小',
      'x-decorator': 'FormItem',
      'x-component': 'Input',
      default: themeStore.theme.fontSize,
    },
  },
};

const handleOk = () => {
  const values = form.value.values;
  themeStore.updateTheme(values);
  emit('ok');
  emit('update:visible', false);
};

const handleCancel = () => {
  emit('cancel');
  emit('update:visible', false);
};

// 监听visible变化，重置表单
watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    form.value.setValues(themeStore.theme);
  }
});
</script> 